//
//  ViewController.m
//  Web
//
//  Created by hh on 15/12/24.
//  Copyright © 2015年 hh. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate, UITextFieldDelegate>
{
    UIWebView *web;
    UIActivityIndicatorView *av;
    UITextField *tf;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    web = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:web];
    web.delegate = self;
    
    tf = [[UITextField alloc] initWithFrame:CGRectMake(15, 0, self.view.frame.size.width - 30, 34)];
    tf.layer.borderWidth = 1;
    tf.layer.cornerRadius = 4;
    tf.delegate = self;
    tf.returnKeyType = UIReturnKeyGo;
    tf.keyboardType = UIKeyboardTypeURL;
    [self.navigationController.navigationBar addSubview:tf];
    
    av = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [av sizeToFit];
    av.center = CGPointMake(self.view.frame.size.width/2.0, self.view.frame.size.height/2.0);
    [self.view addSubview:av];
    
    NSURL *url = [NSURL URLWithString:@"http://www.huanghai.me"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [web loadRequest:request];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    textField.text = textField.text.lowercaseString;
    NSString *urlString = textField.text;
    if (![urlString hasPrefix:@"http://"]) {
        urlString = [@"http://" stringByAppendingString:urlString];
    }
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [web loadRequest:request];
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [av startAnimating];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [av stopAnimating];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [av stopAnimating];
    // 失败的提示
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
